<?php
namespace Admin\Controller;

use Admin\Logic\CashierLogic;
use Admin\Logic\OrderLogic;
use Think\Controller;
use Admin\Logic\MemberLogic;
use Admin\Logic\FoodLogic;
use Admin\Logic\StockLogic;

class CashierController extends Controller
{
    /**
     * 获取就餐中状态数据
     */
    public function index()
    {
        // 获取订单
        $data  = CashierLogic::getOrder();
        $arr = [];
        foreach ($data as $k=>$v){
            $arr[$v['tableid']] = $v['isuse'];
            if($v['isuse'] == 1){
                //就餐中的餐桌
                $arr[] = $v['tableid'];
            }

        }

        $keyword = I('get.keyword', null);
        $where = '';
        if ($keyword) {
            $where['isbox'] = $keyword;
        }
        $cate = M('table')->group('isbox')->select();
        $data = M('table')->where($where)->select();
        foreach ($data as $k=>$v){
            if(in_array($v['id'],$arr)){
                $data[$k]['isuse'] = 1;
            } else {
                $data[$k]['isuse'] = 0;
            }

            if(in_array($v['id'],CashierLogic::getYyTableId())){
                $data[$k]['isyy'] = 1;
            } else {
                $data[$k]['isyy'] = 0;
            }
        }
//        dd($data);

        $this->assign('data', $data);
        $this->assign('cate', $cate);
        $this->display();
    }


    public function getTable()
    {
        $cid=1100;
        $tm=time();
        $str=md5($tm.'jdgldd102ssssss'.'yibmnt1511770872'.$cid);
        $tableid=515;
        $timestamp = mktime(0, 0, 0, date('m'), date('d'), date('Y'));

        //餐台列表信息
        $table_url = "http://vip.vcdes.com/index.php?g=Webs&m=Vdingdan&a=repast&token=yibmnt1511770872&cid=$cid&str=$str&tm=$tm";

        $table_json = http_request($table_url);

        $table_arr = json_decode($table_json,true);
        foreach ($table_arr as $key => &$val) {
            $val['table_name'] = $val['name'];
            $val['t_id'] = $val['id'];
            unset($val['name']);
        }

        //写入到数据库
        if (M('table')->addAll($table_arr)) {
            echo 'success';
        } else {
            echo 'error';
        }
    }

    public function tableData()
    {
        $table_id =  I('get.id');
        $cid=1100;
        $tm=time();
        $token = 'yibmnt1511770872';
        $str=md5($tm.'jdgldd102ssssss'.'yibmnt1511770872'.$cid);

        $url = "http://vip.vcdes.com/index.php?g=Webs&m=Vdingdan&a=orders&token=$token&cid=$cid&str=$str&tm=$tm&tableid=$table_id";


        $table_json = http_request($url);
        $table_arr = json_decode($table_json,true);
        $data = [];

        foreach ($table_arr as $key => $value) {
            if ($value['tableid'] == $table_id) {
                $data = $value;
            }
        }
        $data['info'] = unserialize($data['info']);
        $data['shifu_money'] = $data['havepayed'];
        if (isset($data['reduce_cost'])) { //实付金额
            $data['shifu_money'] = $data['havepayed'] - $data['reduce_cost'];
        }
        //未付金额
        $data['weifu_money'] = $data['price'] - $data['havepayed'];

        $data['json'] = json_encode($data);
        $this->assign('data', $data);
        $this->display();
    }

    public function yyTableData()
    {
        $table_id =  I('get.id');

        $res = CashierLogic::getYyTableData($table_id);
        $data = [];
        foreach ($res as $key => $value) {
            if ($value['tableid'] == $table_id) {
                $data = $value;
            }
        }
        $data['json'] = json_encode($data);
        $allmenu = $data['allmenu'];
        $shifu_money = $data['havepaid'] - $data['reduce_cost'] - $data['tablemoneypaid'];
        $shifu_money = empty($shifu_money) ? 0 : $shifu_money;
        unset($allmenu['table']);
        $this->assign('shifu_money', $shifu_money);
        $this->assign('allmenu', $allmenu);
        $this->assign('data', $data);
        $this->display();

    }

    public function qtjs()
    {

        $order_data = json_decode(I('post.data', '', 'htmlspecialchars_decode'), true);
        $money = I('post.money');
        $sfmoney = I('post.sfmoney');

        $token = 'yibmnt1511770872';
        $suc_id = [];

        $token = I('post.token','yibmnt1511770872', 'htmlspecialchars');

        $cid=1100;
        $startTime = time();
        $tm=time();

        $str=md5($tm.'jdgldd102ssssss'.'yibmnt1511770872'.$cid);
        $url = "http://vip.vcdes.com/index.php?g=Webs&m=Vdingdan&a=cleartable&token=$token&cid=$cid&str=$str&tm=$tm&st[]=".$startTime."&st[]=".$tm.""."&tableid=".$order_data['tableid'];

        $result = http_request($url); //获取源数据

        // 拼装数据
        try{
            $order = '';

            $food_loss = 0;
            $food_sale = 0;

                // 判断是否已存在此订单
                $res = M('Order')
                    ->where(['order_id'=>$order_data['orderid']])
                    ->field(['id'])
                    ->find();
                if(!empty($res)){
                    echo  json_encode(['msg'=>'订单已存在']);
                    return;
                }

                $order = [
                    'order_id'        => $order_data['orderid'],                     //订单编号
                    'order_store'     => $order_data['cid'],      //分店id
                    'customer_name'   => $order_data['name'],       //客户姓名
                    'order_name'   => $order_data['tableid'],       //桌号
                    'order_total'     => $order_data['price'],                  //订单总金额
                    'order_pay'       => $money,           //支付方式
                    'is_pay'          => '已支付',              //支付状态
                    'reserve_state'   => '预约成功',       //预约状态
                    'reserve_time'    => date('Y-m-d H:i:s'),        //预约时间
                    'customer_mobile' => $order_data['tel'],     //客户手机号
                    'order_num'       => $order_data['nums'],           //就餐人数
                    'token'           => $token,               //商家用户
                    'pinglun'         => $order_data['pinglun'],
                    'plxj'            => $order_data['plxj'],
                    'created_at'      => getDateTime(),
                    'sfmoney'         => $sfmoney,
                    'yddkmoney'         => $order_data['tablemoneypaid'],
                    'wfmoney'         => $order_data['notpayprice'],
                    'djqmoney'         => $order_data['reduce_cost'],
                ];

                // 开启事务
                $model = M();
                $model->startTrans();
                $flag = true;

                // 添加订单
                $order_id = D('Order')->add($order);
                if($order_id === false){
                    $flag = false;
                }

                // 添加订单详情(菜谱)
                $info = [];
                $food_id = [];

                unset($order_data['allmenu']['table']);
                foreach ($order_data['allmenu'] as $k=>$v){
                    $foodData = D('food')->where(['name'=>$v['name']])->field(['id','loss'])->find();
                    $foodId = $foodData['id'];
                    $food_id[] = $foodId;
                    $info[] = [
                        'order_id'  => $order_id,
                        'food_id'   => $foodId,
                        'spec'      => empty($v['spec'])?'大':mb_substr($v['spec'],0,1),
                        'num'=>$v['num']
                    ];
                    // 计算出菜谱库存消耗
                    $food_loss_v  = FoodLogic::getStockLoss($foodId,$v['num']) + json_decode($foodData['loss'], true)['大'];
                    $food_loss += $food_loss_v;


                    // 计算出菜谱销售价
                    $food_sale_v = FoodLogic::getFoodPrice($foodId);
                    $food_sale += $food_sale_v;
                }

                // 添加库存详情
                $data = FoodLogic::getOrderFoodStock($food_id);
                $res = D('Order')->where(['id'=>$order_id])->save(['stock_detail'=>json_encode($data)]);

                if($res === false){
                    $flag = false;
                }

                // 添加订单详情的记录
                $detail = D('OrderDetail')->addAll($info);
                if($detail === false){
                    $flag = false;
                }

                // 给订单的成本价和销售价赋值
                $food_loss_sale_data = [
                    'order_cost' => $food_loss,
                    'order_sale' => $food_sale,
                ];
                $food_sale = 0;
                $food_loss = 0;
                $res = D('Order')
                    ->where(['id'=>$order_id])
                    ->save($food_loss_sale_data);
                if($res === false){
                    $flag = false;
                }


                // 减少库存，更新库存流水
                //获取菜谱用了多少材料
                $food = FoodLogic::getFindAll($food_id);
                //更新库存明细表
                $stock_detail = StockLogic::updateDetailOrder($food, $order_id);
                if($stock_detail  === false){
                    $flag = false;
                }




                // 根据传过来的桌号，找到对应餐桌和员工,并添加到订单中
                $table_id = D('Table as t')
                    ->where(['table_name'=>$order_data['tableid']])
                    ->join('left join food_member as m on t.member_id=m.id')
                    ->field(['t.*,m.nickname'])
                    ->find();
                $data = [
                    'person_id'=>$table_id['member_id'],     //餐桌负责员工
                    'person_name'=>$table_id['nickname']     //员工姓名
                ];
                $res = D('Order')
                    ->where(['id'=>$order_id])
                    ->save($data);
                if($res === false){
                    $flag = false;
                }

                //提交
                if ($flag) {
                    $model->commit();
                    $suc_id[] = $order_data['id'];
                } else {
                    $model->rollback();
                }


            echo  json_encode(['msg'=>'成功清算订单为：'.$order_id]);

        } catch (\Exception $e){
            echo  json_encode(['msg'=>'清算失败']);

            return false;
        }

    }

    public function qtjs_jc()
    {
        $order_data = json_decode(I('post.data', '', 'htmlspecialchars_decode'), true);
        $money = I('post.money');
        $sfmoney = I('post.sfmoney');


        $token = 'yibmnt1511770872';
        $suc_id = [];

        $token = I('post.token','yibmnt1511770872', 'htmlspecialchars');

        $cid=1100;
        $startTime = time();
        $tm=time();

        $str=md5($tm.'jdgldd102ssssss'.'yibmnt1511770872'.$cid);
        $url = "http://vip.vcdes.com/index.php?g=Webs&m=Vdingdan&a=cleartable&token=$token&cid=$cid&str=$str&tm=$tm&st[]=".$startTime."&st[]=".$tm.""."&tableid=".$order_data['tableid'];

        $result = http_request($url); //获取源数据
        // 拼装数据
        try{
            $order = '';

            $food_loss = 0;
            $food_sale = 0;

            // 判断是否已存在此订单
            $res = M('Order')
                ->where(['order_id'=>$order_data['orderid']])
                ->field(['id'])
                ->find();
            if(!empty($res)){
                echo  json_encode(['msg'=>'订单已存在']);
                return;
            }

            $order = [
                'order_id'        => $order_data['orderid'],                     //订单编号
                'order_store'     => $order_data['cid'],      //分店id
                'customer_name'   => $order_data['name'],       //客户姓名
                'order_name'   => $order_data['tableid'],       //桌号
                'order_total'     => $order_data['price'],                  //订单总金额
                'order_pay'       => $money,           //支付方式
                'is_pay'          => '已支付',              //支付状态
                'reserve_state'   => '预约成功',       //预约状态
                'reserve_time'    => date('Y-m-d H:i:s'),        //预约时间
                'customer_mobile' => $order_data['tel'],     //客户手机号
                'order_num'       => $order_data['nums'],           //就餐人数
                'token'           => $token,               //商家用户
                'pinglun'         => $order_data['pinglun'],
                'plxj'            => $order_data['plxj'],
                'created_at'      => getDateTime(),
                'sfmoney'         => $order_data['shifu_money'],
                'yddkmoney'         => 0,
                'wfmoney'         => $order_data['weifu_money'],
                'djqmoney'         => $order_data['reduce_cost'],
            ];

            // 开启事务
            $model = M();
            $model->startTrans();
            $flag = true;

            // 添加订单
            $order_id = D('Order')->add($order);
            if($order_id === false){
                $flag = false;
            }

            // 添加订单详情(菜谱)
            $info = [];
            $food_id = [];

            foreach ($order_data['info'] as $k=>$v){
                $foodData = D('food')->where(['name'=>$v['name']])->field(['id','loss'])->find();
                $foodId = $foodData['id'];
                $food_id[] = $foodId;
                $info[] = [
                    'order_id'  => $order_id,
                    'food_id'   => $foodId,
                    'spec'      => empty($v['spec'])?'大':mb_substr($v['spec'],0,1),
                    'num'=>$v['num']
                ];
                // 计算出菜谱库存消耗
                $food_loss_v  = FoodLogic::getStockLoss($foodId,$v['num']) + json_decode($foodData['loss'], true)['大'];
                $food_loss += $food_loss_v;


                // 计算出菜谱销售价
                $food_sale_v = FoodLogic::getFoodPrice($foodId);
                $food_sale += $food_sale_v;
            }

            // 添加库存详情
            $data = FoodLogic::getOrderFoodStock($food_id);
            $res = D('Order')->where(['id'=>$order_id])->save(['stock_detail'=>json_encode($data)]);

            if($res === false){
                $flag = false;
            }

            // 添加订单详情的记录
            $detail = D('OrderDetail')->addAll($info);
            if($detail === false){
                $flag = false;
            }

            // 给订单的成本价和销售价赋值
            $food_loss_sale_data = [
                'order_cost' => $food_loss,
                'order_sale' => $food_sale,
            ];
            $food_sale = 0;
            $food_loss = 0;
            $res = D('Order')
                ->where(['id'=>$order_id])
                ->save($food_loss_sale_data);
            if($res === false){
                $flag = false;
            }


            // 减少库存，更新库存流水
            //获取菜谱用了多少材料
            $food = FoodLogic::getFindAll($food_id);
            //更新库存明细表
            $stock_detail = StockLogic::updateDetailOrder($food, $order_id);
            if($stock_detail  === false){
                $flag = false;
            }




            // 根据传过来的桌号，找到对应餐桌和员工,并添加到订单中
            $table_id = D('Table as t')
                ->where(['table_name'=>$order_data['tableid']])
                ->join('left join food_member as m on t.member_id=m.id')
                ->field(['t.*,m.nickname'])
                ->find();
            $data = [
                'person_id'=>$table_id['member_id'],     //餐桌负责员工
                'person_name'=>$table_id['nickname']     //员工姓名
            ];
            $res = D('Order')
                ->where(['id'=>$order_id])
                ->save($data);
            if($res === false){
                $flag = false;
            }

            //提交
            if ($flag) {
                $model->commit();
                $suc_id[] = $order_data['id'];
            } else {
                $model->rollback();
            }


            echo  json_encode(['msg'=>'成功清算订单为：'.$order_id]);

        } catch (\Exception $e){
            var_dump($e->getMessage());
            echo  json_encode(['msg'=>'清算失败']);

            return false;
        }

    }




}